import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lcrealtime/Common/Global.dart';
import 'package:lcrealtime/States/GlobalEvent.dart';
import 'package:leancloud_official_plugin/leancloud_plugin.dart';
import 'package:leancloud_storage/leancloud.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:flutter_plugin_record/index.dart';

class UIPage extends StatefulWidget {
  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<UIPage> {
  var _listController = new ScrollController();
  TextEditingController _messController = new TextEditingController();

  var list;
  @override
  void initState() {
    String jsonStr = '[{"name":"张三"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"张三"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"张三"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"},{"name":"李四"}]';
    list = json.decode(jsonStr);

    super.initState();
    Timer(Duration(seconds: 3), () { //callback function
      _listController.jumpTo(_listController.position.maxScrollExtent);
    });
  }

  test(){
    _listController.animateTo( 100.0, duration: new Duration(milliseconds: 300), curve: Curves.bounceIn,);
    list.add(json.decode('{"name":"张三"}'));
    setState(() {});
    Timer(Duration(seconds: 1), () { //callback function
      _listController.jumpTo(_listController.position.maxScrollExtent);
    });


  }
  // 主体页面进行 数据发送,监听接收数据,选择图片 发送图片
  @override
  Widget build(BuildContext context) {
    print(list.length);
    return Scaffold(
        appBar:AppBar(title: Text('聊天页面'),centerTitle:true) ,
        bottomSheet:  _bottomSheet(),
        body: Form( //
            child:Container(
                padding:  EdgeInsets.fromLTRB(15, 30, 15, 110),
                child: ListView.builder(
                  controller: _listController,
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    return renderline(index);
                  },
                )) ));
  }

  Widget _bottomSheet(){
    return  Container(
      decoration: new BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
        border: new Border.all(width: 1, color: Colors.white),
      ),
      height: 100,
      width:  MediaQuery.of(context).size.width * 1,
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
      child:Column( children: [
        Row(
            children: [
              Icon(Icons.add, size: 50.0, color: Colors.blue),
              SizedBox(
                width:  MediaQuery.of(context).size.width * 0.6,
                child: TextField(
                  controller: _messController,
                  decoration: InputDecoration(
                    labelText: "用户名",
                  ),
                ),
              ),
              RaisedButton(
                child: Text("发送"),
                onPressed: () {
                  sendTextMessage();
                },
              )
            ]),
      ]),
    );
  }
  Widget  renderline(index){
    var type = index%2 ==0;
    if(type)
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          SizedBox(
            width:  MediaQuery.of(context).size.width * 0.6,
            child: Image.network("https://www.baidu.com/img/540x258_2179d1243e6c5320a8dcbecd834a025d.png"),
          ),
          Icon(Icons.sms, size: 50.0, color: Colors.blue),
        ],
      );
    else
      return Row(
        children: <Widget>[
          Icon(Icons.access_alarm, size: 50.0, color: Colors.blue),
          SizedBox(
            width:  MediaQuery.of(context).size.width * 0.6,
            child: Text('聊天页面聊天页面聊天页面聊天页面聊天页面聊天页面聊天页面聊天页面' + index.toString()),
          ),
        ],
      );
  }
  /*********************************/
  void sendTextMessage() async {
    Client currentClient = Client(id: "Bob");
    Set<String> _selectedClientList = new Set();
    _selectedClientList.add("1233");
    Conversation conversation = await currentClient.createConversation(  isUnique: true,  members: _selectedClientList,  name: 'Bob发起群聊');
    _messController.text = "_messController123";
    if (_messController.text != null && _messController.text != '') {
      try {
        TextMessage textMessage = TextMessage();
        textMessage.text = _messController.text;
        print(textMessage.text);
        await conversation.send(message: textMessage);
        mess.emit(MyEvent.NewMessage, textMessage);
      } catch (e) {
        showToastRed(e.toString());
        print(e.toString());
      }
    } else {
      showToastRed('未输入消息内容');
      return;
    }
  }
}
